package com.cn.server.tcp;

import com.cn.common.core.model.Request;
import com.cn.common.core.session.Session;
import com.cn.common.core.session.SessionImpl;
import com.cn.common.core.session.SessionManager;
import com.cn.server.module.login.ImUser;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 消息接受处理类
 */
public class ServerHandler extends SimpleChannelInboundHandler<Request> {

    private MessageDispatcher messageDispatcher;

    public ServerHandler(MessageDispatcher messageDispatcher) {
        this.messageDispatcher = messageDispatcher;
    }

    /**
     * 接收消息
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Request request) throws Exception {

        handlerMessage(new SessionImpl(ctx.channel()), request);
    }


    /**
     * 消息处理
     *
     * @param session
     * @param request
     */
    private void handlerMessage(Session session, Request request) {
        System.out.println("module:" + request.getModule() + "   " + "cmd：" + request.getCmd());
        messageDispatcher.onReceive(request, session);
    }

    /**
     * 断线移除会话
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Session session = new SessionImpl(ctx.channel());
        Object object = session.getAttachment();
        if (object != null) {
            ImUser imUser = (ImUser) object;
            SessionManager.removeSession(imUser.getLoginName());
        }
    }
}
